#coding=utf-8

KIND = 16
#BASE = ord('a')

class Node():
    def __init__(self):
        self.fail = None
        self.next = [None]*KIND
        self.end = False

class AC_Automachine():
    def __init__(self):
        self.root = Node()
        self.queue = []
        
    def getIndex(self,char):
        return ord(char)# - BASE
    
    def insert(self,string):
        p = self.root
        for char in string:
            index = self.getIndex(char)
            if p.next[index] == None:
                p.next[index] = Node()
            p = p.next[index]
        p.end = True
        
    def build_automachine(self):
        self.root.fail = None
        self.queue.append(self.root)
        while len(self.queue)!=0:
            parent = self.queue[0]
            self.queue.pop(0)
            for i,child in enumerate(parent.next):
                if child == None:continue
                if parent == self.root:
                    child.fail = self.root
                else:
                    failp = parent.fail
                    while failp != None:
                        if failp.next[i] != None:
                            child.fail = failp.next[i]
                            break
                        failp = failp.fail
                    if failp==None: child.fail=self.root
                self.queue.append(child)
                
    def matchOne(self,string):
        p = self.root
        for char in string:
            index = self.getIndex(char)
            while p.next[index]==None and p!=self.root: p=p.fail
            if p.next[index]==None:p=self.root
            else: p=p.next[index]
            if p.end:return True
        return False
    
    


class UnicodeAC_AutoMachine():
    def __init__(self):
        self.ac = AC_Automachine()
        
    def getAcString(self,string):
        string = bytearray(string.encode('utf-8'))
        ac_string = ''
        for byte in string:
            ac_string += chr(byte%16)
            ac_string += chr(byte/16)
        #print ac_string
        return ac_string
    
    def insert(self,string):
        if type(string) != unicode:
            raise Exception('UnicodeAC_AutoMachine:: insert type not unicode')
        ac_string = self.getAcString(string)
        self.ac.insert(ac_string)

    def build_automachine(self):
        self.ac.build_automachine()
    
    def matchOne(self,string):
        if type(string) != unicode:
            raise Exception('UnicodeAC_AutoMachine:: insert type not unicode')
        ac_string = self.getAcString(string)
        return self.ac.matchOne(ac_string)
    


def main2():
    ac = UnicodeAC_AutoMachine()
    ac.insert(u'丁亚光')
    ac.insert(u'好吃的')
    ac.insert(u'好玩的')
    ac.build_automachine()
    print ac.matchOne(u'hi,丁亚光在干啥')
    print ac.matchOne(u'ab')
    print ac.matchOne(u'不能吃饭啊')
    print ac.matchOne(u'饭很好吃，有很多好好的吃的，')
    print ac.matchOne(u'有很多好玩的')

if __name__ == '__main__':
    main2()
    
